package com.iona.json.builders;

import java.util.List;

import com.iona.domain.Discipline;
import com.iona.domain.DisciplinePurview;
import com.iona.domain.Purview;
import com.iona.json.JSONArray;
import com.iona.json.JSONBuilder;
import com.iona.json.JSONException;

public class PivotBuilder extends JSONBuilder {
	public static final String NAME = "disciplines";
	private final List<Discipline> disciplines;
	private final List<Purview> purviews;

	public PivotBuilder(List<Discipline> disciplines,
			List<Purview> purviews) {
		this.disciplines = disciplines;
		this.purviews = purviews;
	}

	@Override
	public Object build() throws JSONException {
		JSONArray root = new JSONArray();
		for (Discipline d : disciplines) {
			for (Purview p : purviews) {
				JSONArray arr = new JSONArray();
				arr.put(d.getName());
				arr.put(p.getName());
				arr.put(checkIfRelationshipExist(d, p));
				root.put(arr);
			}
		}
		return root;
	}

	private String checkIfRelationshipExist(Discipline d, Purview p) {
		List<DisciplinePurview> purviewList = d.getPurviewList();
		for (DisciplinePurview dp : purviewList) {
			if(dp.getPurview().equals(p)){
				return "yes";
			}
		}
		return "no";
//		DisciplinePurview dp = new DisciplinePurviewDAO()
//				.findByDisciplineAndPurview(d, p);
//		return dp == null ? "no" : "yes";
	}

	@Override
	public String name() {
		return NAME;
	}

}
